package JVM;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    public static class myThread extends Thread{
        private Semaphore semaphore;

        public myThread(Semaphore s){
            this.semaphore=s;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                Thread.sleep(1000000);
                System.out.println("当前线程是"+Thread.currentThread().getName()+"----"+"left:"+semaphore.availablePermits());
                System.out.println(semaphore.getQueueLength());
                Random random=new Random();
                Thread.sleep(random.nextInt(1000));
                semaphore.release();
                System.out.println(Thread.currentThread().getName()+"释放资源了！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Semaphore s=new Semaphore(1);
        s.acquire();
        new myThread(s).start();
        new myThread(s).start();

    }
}
